package com.jl.commons.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义的权限校验过滤器
 * 在ShiroConfig中使用
 * 但是如果使用的是自定义的过滤器则无法捕获没有权限的异常
 */
public class ShiroFilter extends AuthorizationFilter {
	
	protected final Logger logger = LoggerFactory.getLogger(ShiroFilter.class);

	@Override
	protected boolean isAccessAllowed(ServletRequest request,ServletResponse response, Object handler) throws Exception {
		//请求路径
		String permissionUrl = ((HttpServletRequest)request).getServletPath();
		if(StringUtils.isEmpty(permissionUrl)){
			return false;
		}
		//请求方法
		String permissionMethod = permissionUrl.substring(permissionUrl.lastIndexOf("/")==-1 ? 0 : permissionUrl.lastIndexOf("/")+1).split("\\.")[0];
		boolean isIgn = StringUtils.isNotEmpty(permissionMethod) && (permissionMethod.equalsIgnoreCase("index") || permissionMethod.startsWith("ign"));
		if(isIgn){
			return true;
		}
		// 权限校验
		if (this.getSubject(request, response).isPermitted(permissionUrl)) {
			return true;
		}
		logger.error("你没有访问权限："+permissionUrl);
		return false;
	}

}
